/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    struct cmp{
        
        bool operator () (ListNode* p1,ListNode* p2){
            return p1->val>p2->val;
        }
    };
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        
        priority_queue<ListNode*,vector<ListNode*>,cmp> q;
        ListNode dummy;
        ListNode* cur=&dummy;
        for(int i=0;i<lists.size();++i){
            if(lists[i]!=nullptr){
                q.push(lists[i]);
            }
        }
        while(q.size()){
            ListNode* u=q.top();
            q.pop();
            if(nullptr != u->next){
                q.push(u->next);
            }
            cur->next=u;
            cur=cur->next;
        }

        return dummy.next;
    }
};
